//
//  RefrshHeader.swift
//  YehwangPro
//
//  Created by Yehwang Developer on 2022/3/9.
//

import Foundation
import Lottie
import MJRefresh
import UIKit

class RefrshHeader: MJRefreshHeader {
    private var loading: LottieAnimationView!
    
    override func prepare() {
        super.prepare()
        mj_h = 50
        
        loading = LottieAnimationView(name: "loading")
        loading.autoresizingMask = [.flexibleHeight, .flexibleWidth]
        loading.contentMode = .scaleAspectFill
        loading.loopMode = .loop
        loading.backgroundBehavior = .pauseAndRestore
        loading.transform = CGAffineTransform(scaleX: -1, y: 1)
        loading.isHidden = true
        addSubview(loading)
    }
    
    override func placeSubviews() {
        super.placeSubviews()
        loading.frame = CGRect(x: (self.mj_w-70)*0.5, y: (self.mj_h-70)*0.5, width: 70, height: 70)
    }
    
    override var state: MJRefreshState {
        didSet {
            switch state {
            case .idle:
                loading.stop()
            case .pulling:
                break
            case .refreshing:
                loading.play(completion: nil)
            default:
                break
            }
        }
    }
    
    override var pullingPercent: CGFloat {
        didSet {
            loading.currentProgress = max(min(pullingPercent, 1.0), 0.0)
            
            if oldValue != pullingPercent {
                if oldValue == 1.0, pullingPercent == 0.0 {
                    UIView.animate(withDuration: 0.25, delay: 0) {
                        // 避免有些导航栏是透明的，会显示刷新头部
                        self.loading.alpha = 0
                    } completion: { _ in
                        self.loading.isHidden = true
                    }
                } else {
                    loading.alpha = 1
                    loading.isHidden = pullingPercent == 0.0
                }
            }
        }
    }
    
    // 监听scrollView的contentOffset改变
    override func scrollViewContentOffsetDidChange(_ change: [AnyHashable: Any]!) {
        super.scrollViewContentOffsetDidChange(change)
    }
     
    // 监听scrollView的contentSize改变
    override func scrollViewContentSizeDidChange(_ change: [AnyHashable: Any]!) {
        super.scrollViewContentSizeDidChange(change)
    }
     
    // 监听scrollView的拖拽状态改变
    override func scrollViewPanStateDidChange(_ change: [AnyHashable: Any]!) {
        super.scrollViewPanStateDidChange(change)
    }
}

class RefrshFooter: MJRefreshAutoNormalFooter {
    override func prepare() {
        super.prepare()
        isRefreshingTitleHidden = true
    }
}
